//
//  AppDelegate.m
//  SKaURobot
//
//  Created by cdong on 16/2/17.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "AppDelegate.h"
#import "SKLoginVController.h"
#import "MZGuidePages.h"
#import "FLAnimatedImage.h"
#import "SKFirstVController.h"
#import "AFHTTPSessionManager.h"
#import "SKRegisterVController.h"
#import "isConnectNet.h"
#import "growthPhotosVController.h"
#import <SystemConfiguration/CaptiveNetwork.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    // [NSThread sleepForTimeInterval:3.0];
    // 设置状态栏的样式
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UIApplication sharedApplication].statusBarHidden = NO;
    
//    growthPhotosVController *growth = [[growthPhotosVController alloc]init];
//    self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[growthPhotosVController alloc]init]];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    [userDefaults setObject:@"23" forKey:@"password"];
    NSString *userName = [userDefaults objectForKey:@"userName"];
    NSString *pwd = [userDefaults objectForKey:@"password"];
//    if (!((userName == nil || userName == NULL) && (pwd == nil || pwd == NULL)) ){
//        if (!isConnectionAvailable()) { // 网络不通，直接进入未连接主页
//            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKFirstVController alloc]init]];
//        }else{
//            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKLoginVController alloc]init]];
//            [self loginAgainJudge];
//        }
//        
//    }else{
//        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKLoginVController alloc]init]];
//    }
    
    self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKLoginVController alloc]init]];
    
    NSString *launched = [userDefaults objectForKey:@"launched"];
    if (!launched)
    {
        [self guidePages];
        launched = @"YES";
        [userDefaults setObject:launched forKey:@"launched"];
        [userDefaults synchronize];
    }
    return YES;
}

// 首次安装引导
- (void)guidePages
{
    NSString *newPath=[[NSBundle mainBundle] pathForResource:@"tuzhi1.gif" ofType:nil];
    FLAnimatedImage *image1 = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfFile:newPath]];
    FLAnimatedImage *image2 = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tuzhi2.gif" ofType:nil]]];
    FLAnimatedImage *image3 = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tuzhi3.gif" ofType:nil]]];
    FLAnimatedImage *image4 = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tuzhi4.gif" ofType:nil]]];

    NSArray *imageArray = @[image1, image2, image3, image4];
    MZGuidePages *mzgpc = [[MZGuidePages alloc] init];
    mzgpc.imageDatas = imageArray;
    __weak typeof(MZGuidePages) *weakMZ = mzgpc;
    mzgpc.buttonAction = ^{
        [UIView animateWithDuration:2.0f
                         animations:^{
                             weakMZ.alpha = 0.0;
                         }
                         completion:^(BOOL finished) {
                             [weakMZ removeFromSuperview];
                         }];
    };
    [self.window addSubview:mzgpc];
}

int codeRRFF = 0;

- (void)loginAgainJudge{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userName = [userDefaults objectForKey:@"userName"];
    NSString *pwd = [userDefaults objectForKey:@"password"];
    NSString *urlStr =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=login&userName=%@&password=%@",userName,pwd];
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
   
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKFirstVController alloc]init]];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *uid = [responseObject objectForKey:@"uid"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        NSString *sesskey = [responseObject objectForKey:@"sesskey"];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:uid forKey:@"uid"];
        [defaults setObject:sesskey forKey:@"sesskey"];
        if (error.integerValue == 0) {
            NSUserDefaults *userdefaut = [NSUserDefaults standardUserDefaults];
            if (errorCode.integerValue == 1031) { // 老用户未绑定手机号跳转
                codeRRFF = 103;
                [userdefaut setInteger:codeRRFF forKey:@"registerOrGetCode"];
                self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKRegisterVController alloc]init]];

            }else{
                SKFirstVController *ff = [[SKFirstVController alloc]init];
                ff.updateUIFlag = YES;
                self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKFirstVController alloc]init]];
            }
            
        }else{ // 用户在其他客户端修改用户信息，导致此次登录失败
            
            if (errorCode.integerValue == 1010) { // 用户名或手机号错误
                self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKLoginVController alloc]init]];
            }if (errorCode.integerValue == 1011) { // 密码错误
                self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKLoginVController alloc]init]];
            }else{
                self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKLoginVController alloc]init]];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[SKFirstVController alloc]init]];
    }];
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//    [[NSNotificationCenter defaultCenter] postNotificationName:@" postData "　object:@"getWifiSSID"];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(getWifiSSID)
//                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (NSMutableArray *)getWifiSSID{
    NSMutableArray *wifiArray = [[NSMutableArray alloc]init];
    // 获取Wi-Fi
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    NSLog(@"Supported interfaces: %@", ifs);
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        [wifiArray addObject:info[@"SSID"]];
        NSLog(@"%@ => %@", ifnam, info);  //单个数据info[@"SSID"]; info[@"BSSID"];
        if (info && [info count]) { break; }
    }
    return wifiArray;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//- (void)dealloc{
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

@end
